/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.apache.spark.examples.ml;

import org.apache.spark.ml.feature.BucketedRandomProjectionLSH;
import org.apache.spark.ml.feature.BucketedRandomProjectionLSHModel;
import org.apache.spark.ml.linalg.Vector;
import org.apache.spark.ml.linalg.VectorUDT;
import org.apache.spark.ml.linalg.Vectors;
import org.apache.spark.sql.Dataset;
import org.apache.spark.sql.Row;
import org.apache.spark.sql.RowFactory;
import org.apache.spark.sql.SparkSession;
import org.apache.spark.sql.types.DataTypes;
import org.apache.spark.sql.types.Metadata;
import org.apache.spark.sql.types.StructField;
import org.apache.spark.sql.types.StructType;

import java.util.Arrays;
import java.util.List;

import static org.apache.spark.sql.functions.col;
// $example off$
/**
 * 一个展示BucketedRandomProjectionLSH用法的示例。
 * 运行方式：
 *   bin/run-example ml.JavaBucketedRandomProjectionLSHExample
 */
public class JavaBucketedRandomProjectionLSHExampleZH {
  public static void main(String[] args) {
    // 创建SparkSession对象
    SparkSession spark = SparkSession
      .builder()
      .appName("JavaBucketedRandomProjectionLSHExample")
      .getOrCreate();

    // 构造数据集A
    List<Row> dataA = Arrays.asList(
      RowFactory.create(0, Vectors.dense(1.0, 1.0)),  // ID为0，特征向量为(1.0, 1.0)
      RowFactory.create(1, Vectors.dense(1.0, -1.0)), // ID为1，特征向量为(1.0, -1.0)
      RowFactory.create(2, Vectors.dense(-1.0, -1.0)),// ID为2，特征向量为(-1.0, -1.0)
      RowFactory.create(3, Vectors.dense(-1.0, 1.0))  // ID为3，特征向量为(-1.0, 1.0)
    );

    // 构造数据集B
    List<Row> dataB = Arrays.asList(
      RowFactory.create(4, Vectors.dense(1.0, 0.0)),  // ID为4，特征向量为(1.0, 0.0)
      RowFactory.create(5, Vectors.dense(-1.0, 0.0)), // ID为5，特征向量为(-1.0, 0.0)
      RowFactory.create(6, Vectors.dense(0.0, 1.0)),  // ID为6，特征向量为(0.0, 1.0)
      RowFactory.create(7, Vectors.dense(0.0, -1.0))  // ID为7，特征向量为(0.0, -1.0)
    );

    // 定义数据结构模式
    StructType schema = new StructType(new StructField[]{
      new StructField("id", DataTypes.IntegerType, false, Metadata.empty()), // ID字段
      new StructField("features", new VectorUDT(), false, Metadata.empty())  // 特征向量字段
    });

    // 创建DataFrame
    Dataset<Row> dfA = spark.createDataFrame(dataA, schema);
    Dataset<Row> dfB = spark.createDataFrame(dataB, schema);

    // 定义一个查询关键点
    Vector key = Vectors.dense(1.0, 0.0);

    // 创建并配置BucketedRandomProjectionLSH模型
    BucketedRandomProjectionLSH mh = new BucketedRandomProjectionLSH()
      .setBucketLength(2.0)  // 设置桶的长度
      .setNumHashTables(3)   // 设置哈希表的数量
      .setInputCol("features") // 设置输入列名
      .setOutputCol("hashes"); // 设置输出列名

    // 训练模型
    BucketedRandomProjectionLSHModel model = mh.fit(dfA);

    // 特征转换
    System.out.println("存储哈希值在'hashes'列的哈希数据集：");
    model.transform(dfA).show();

    // 计算输入行的局部敏感哈希，然后执行近似相似度连接
    System.out.println("近似连接dfA和dfB，距离小于1.5：");
    model.approxSimilarityJoin(dfA, dfB, 1.5, "EuclideanDistance")
      .select(col("datasetA.id").alias("idA"),
        col("datasetB.id").alias("idB"),
        col("EuclideanDistance")).show();

    // 计算输入行的局部敏感哈希，然后执行近似最近邻搜索
    System.out.println("近似搜索dfA中与关键点最近的2个邻居：");
    model.approxNearestNeighbors(dfA, key, 2).show();

    // 停止SparkSession
    spark.stop();
  }
}